
#include "MH_Z1X.h"

MH_Z1X::MH_Z1X(){
    
}

// 使用PWM读取数据
void MH_Z1X::read_PWM(int pin){
    pinMode(pin, INPUT);
    unsigned long TH;//定义高电平输出变量
    TH = pulseIn(pin, HIGH);//读取一个周期内高电平输出变量
    if (TH < 4000)//PWM高电平输出小于4000us时，返回重新读数
    {
        i_error++;
        if(i_error >= ERROR_MAX){
            i_error = 0;
            co2 = 0;
            return;
        } else
            read_PWM(pin);
    }
    else
    {
        co2 = 5 * (TH - 2000) / 1000;//换算成CO2浓度
    }  
}

// 使用串口读取数据    
#ifdef MH_Z1X_USE_SOFTWARE_SERIAL
MH_Z1X::MH_Z1X(SoftwareSerial &uart): m_puart(&uart)
{
    m_puart->begin(9600);
}
#else
MH_Z1X::MH_Z1X(HardwareSerial &uart): m_puart(&uart)
{
    m_puart->begin(9600);
}
#endif 
   
void MH_Z1X::read(){
  int i = 0;
  int j = 0;
  byte b1[] = {0xff, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79};
  byte b2[9] = {0};
#ifdef MH_Z1X_USE_SOFTWARE_SERIAL
  m_puart->listen();
#endif
  for (i = 0; i < 9; i++) {
    m_puart->write(b1[i]);
  }
  i = 0;
  while (m_puart->available() > 0) {
    b2[i] = m_puart->read();
    i++;
    if (i >= 9) break;
  }
  j = b2[1] + b2[2] + b2[3] + b2[4] + b2[5] + b2[6] + b2[7];
  j = 0xff - byte(j) + 1;
#ifdef DEBUG
  Serial.print(b2[0], HEX); p_null();
  Serial.print(b2[1], HEX); p_null();
  Serial.print(b2[2], HEX); p_null();
  Serial.print(b2[3], HEX); p_null();
  Serial.print(b2[4], HEX); p_null();
  Serial.print(b2[5], HEX); p_null();
  Serial.print(b2[6], HEX); p_null();
  Serial.print(b2[7], HEX); p_null();
  Serial.print(b2[8], HEX); p_null();

  Serial.print(j, HEX); p_null();
  Serial.print(i_error); p_null();
  Serial.println();
#endif
  if (j > 0 && j == b2[8]) {
    i_error = 0;
    co2 = b2[2] * 0x100 + b2[3];
  } else if (i_error >= ERROR_MAX) {
    i_error = 0;
    co2 = 0;
  } else {
    i_error++;
    delay(200);
    read();
  }
}

